package com.mall.order.services;

import com.mall.order.CancelOrderService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.order.dto.PostCancelOlderRequest;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author : PengFei Zhang
 * @Data :2021/6/18  22:29
 * @Description :
 */
//订单取消  zpf
@Service
public class CancelOrderServiceImpl implements CancelOrderService {

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public CancelOrderResponse cancelOrder(PostCancelOlderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        try {
            Example example = new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId", request.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            Order order = orderMapper.selectByPrimaryKey(request.getOrderId());
            order.setStatus(7);
            orderMapper.updateByPrimaryKey(order);
            for (OrderItem orderItem : orderItems) {
                OrderItem  orderItemtemp=orderItem;
                orderItemtemp.setStatus(2);
                orderItemMapper.updateByPrimaryKey( orderItemtemp);
                //库存变化
                Stock stock = stockMapper.selectStock(orderItem.getItemId());
                //锁定库存
                stock.setLockCount(stock.getLockCount() - orderItem.getNum());
                //库存
                stock.setStockCount(stock.getStockCount() + orderItem.getNum());

                stockMapper.updateByPrimaryKey(stock);
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
            return response;
        } catch (Exception e) {
            response.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
            return response;
        }
    }
}
